package com.ocom.webapi.controller;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.dto.UnitsPageOnShowDto;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetCompanySummaryRequest;
import com.ocom.common.request.web.ReplaceTokenRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.common.vo.webapi.ComIdVo;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.OauthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class OcomTechController {

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private OauthService oauthService;

    @Value("${platformSecret}")
    private String platformSecret;

    //获取WEB页面列表
    @PostMapping(WebApiServiceUrl.URL_OcomTechCompanyList)
    public Result getCompanySummary(@RequestBody GetCompanySummaryRequest getCompanySummaryRequest) {
        return companyClientService.getCompanySummary(getCompanySummaryRequest);
    }

    //获取代理商列表（OcomTech/agentList）
    @PostMapping(WebApiServiceUrl.URL_OcomTechAgentList)
    public Result ocomTechAgentList(@RequestBody JSONObject jsonObject) {
        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        if (StringUtils.isNotEmpty(jsonObject.getString("agentName"))){
            companyListInfoVo.setComName(jsonObject.getString("agentName"));
        }
        companyListInfoVo.setOnly(1);
        companyListInfoVo.setPage(1);
        companyListInfoVo.setSize(500);
        Result result=companyClientService.GetCompanyListInfo(companyListInfoVo);
        if (result.getCode()==200){
            JSONObject resultJsonObject= JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
            List<UnitsPageOnShowDto> list = JSONArray.parseArray(JSON.toJSONString(resultJsonObject.get("list")) , UnitsPageOnShowDto.class);
            List<JSONObject> objectList=new ArrayList<>();
            for (UnitsPageOnShowDto unitsPageOnShowDto : list) {
                JSONObject reJsonObject=new JSONObject();
                reJsonObject.put("agentId",unitsPageOnShowDto.getComId());
                reJsonObject.put("agentName",unitsPageOnShowDto.getAgentName());
                reJsonObject.put("province",unitsPageOnShowDto.getProvince());
                reJsonObject.put("city",unitsPageOnShowDto.getCity());
                objectList.add(reJsonObject);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("list",objectList);
            return ResultUtil.success(map);
        }else {
            return result;
        }
    }

    //3.1.3登入单位（OcomTech/companyLogin）
    @PostMapping(WebApiServiceUrl.URL_OcomTechCompanyLogin)
    public Result companyLogin(@RequestBody ComIdVo comIdVo) {

        Long role = SecurityUtils.getYoCiUser().getRole();
        if (role != 0l && role != 1l) {
            if(!SecurityUtils.getYoCiUser().getPermissions().contains("sys:user:master")){
                return ResultUtil.error(ResultEnum.Err_4);
            }
        }

        Result result = oauthService.login(
            "replace_token",
                "client_6",
                "123456",
                SecurityUtils.getToken(),
                comIdVo.getComId()
        );
        if(result.getCode()!=200){
            return result;
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));


        Map<String , Object> resMap =new HashMap<>();

        resMap.put("token",jsonObject.get("access_token"));

        resMap.put("menuTree",new ArrayList<>());


        Result result1  = companyClientService.GetCompanyListInfoOne(comIdVo.getComId());

        if(result1.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_301);
        }
        EntityCompanyList entityCompanyList =JSON.parseObject(JSON.toJSONString(result1.getData()),EntityCompanyList.class);
        resMap.put("comName",entityCompanyList.getComName());


        JSONObject jsonObject1 =new JSONObject();
        jsonObject1.put("saasNo",entityCompanyList.getSaasId());
        jsonObject1.put("xfVer",entityCompanyList.getXfStatus());
        jsonObject1.put("mjVer",entityCompanyList.getMjStatus());
        jsonObject1.put("role",21);
        Result result2 = humanClientService.getSaasMenuByRole(jsonObject1);

        if(result2.getCode()==200){
            JSONObject jsonObject3 = JSON.parseObject(JSON.toJSONString(result2.getData()));
            resMap.put("menuTree",jsonObject3.get("menuTree"));
        }

        return ResultUtil.success(resMap);

    }





    //3.1.3.1登入单位（OcomTech/companyLoginB）
    @PostMapping(WebApiServiceUrl.URL_OcomTechCompanyLoginB)
    public Result companyLoginB(@RequestBody ReplaceTokenRequest request) {

        Long role = SecurityUtils.getYoCiUser().getRole();
        if (role != 0l && role != 1l) {
            if(!SecurityUtils.getYoCiUser().getPermissions().contains("sys:user:master")){
                return ResultUtil.error(ResultEnum.Err_4);
            }
        }

        Result result3 = humanClientService.getMngUserInfoById(request.getId());

        if(result3.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_303);
        }

        EntityMngUserInfo entityMngUserInfo = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityMngUserInfo.class);


        //下载hutool依赖
        String key = "tbk0Xa67cEePvv14g5Pf1MPzIceQMN14"; // 密钥（8 字节）
        String username = entityMngUserInfo.getUserName();
        String password = platformSecret;
        username = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).encryptBase64(username);
        password = SecureUtil.des(key.getBytes(StandardCharsets.UTF_8)).encryptBase64(password);
        username = new String(HexUtil.encodeHex(username.getBytes(StandardCharsets.UTF_8)));
        password =  new String(HexUtil.encodeHex(password.getBytes(StandardCharsets.UTF_8)));

        Result result = oauthService.loginWeb(
                username,
                password ,
                entityMngUserInfo.getRole().toString(),
                "code_auth",
                "client_1",
                "123456"
        );

        if(result.getCode()!=200){
            return result;
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));


        Map<String , Object> resMap =new HashMap<>();

        resMap.put("token",jsonObject.get("access_token"));

        resMap.put("menuTree",new ArrayList<>());


        Result result1  = companyClientService.GetCompanyListInfoOne(entityMngUserInfo.getComId());

        if(result1.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_301);
        }
        EntityCompanyList entityCompanyList =JSON.parseObject(JSON.toJSONString(result1.getData()),EntityCompanyList.class);
        resMap.put("comName",entityCompanyList.getComName());


        JSONObject jsonObject1 =new JSONObject();
        jsonObject1.put("saasNo",entityCompanyList.getSaasId());
        jsonObject1.put("xfVer",entityCompanyList.getXfStatus());
        jsonObject1.put("mjVer",entityCompanyList.getMjStatus());
        jsonObject1.put("role",entityMngUserInfo.getRole());
        Result result2 = humanClientService.getSaasMenuByRole(jsonObject1);

        if(result2.getCode()==200){
            JSONObject jsonObject3 = JSON.parseObject(JSON.toJSONString(result2.getData()));
            resMap.put("menuTree",jsonObject3.get("menuTree"));
        }

        return ResultUtil.success(resMap);

    }



}
